package cn.ctbu.simple_score_manage.filter;

import cn.ctbu.simple_score_manage.common.R;
import cn.ctbu.simple_score_manage.common.REnum;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 过滤器
 * 检查用户是否已经完成登录
 * 所有路径都进行检查
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        if(true){
            log.info("测试用,放行");
            chain.doFilter(request, response);
            return;
        }
//        获取本次请求的URL
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        //判断是否需要处理
//        log.info("获取到uri,为{}", requestURI);
        //设置不需处理的路径
        String[] urls = new String[]{
                "/api/teacher/login",
                "/api/teacher/logout",
                "/api/student/login",
                "/api/student/logout"
//                设置静态资源访问权限
//                "/static/**",

        };
        boolean check = check(urls, requestURI);
        if (check) {
            //不需处理,直接放行
//            log.info("不需处理,已放行");
            chain.doFilter(request, response);
            return;
        }
        //需要判断是否已经登录,如果登录,则放行
        Object id = ((HttpServletRequest) request).getSession().getAttribute("id");
        if (id != null) {
//            已经登录
            log.info("用户"+id+"已经登录,放行");
            chain.doFilter(request, response);
        }else{
            log.info("未登录,拒绝请求");
            //如果未登录,需要返回未登录结果
            byte[] bytes = JSON.toJSONString(R.error(REnum.NEED_LOGIN)).getBytes(StandardCharsets.UTF_8);
            String s = new String(bytes, StandardCharsets.ISO_8859_1);
            response.getWriter().write(s);
        }

    }

    /**
     * 进行本次请求的路径匹配
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }
}

